package cn.edkuir.cart.service.impl;

import cn.edkuir.cart.feign.ProductFeignService;
import cn.edkuir.cart.interceptor.CartInterceptor;
import cn.edkuir.cart.service.CartService;
import cn.edkuir.cart.vo.CartItem;
import cn.edkuir.cart.vo.CartVo;
import cn.edkuir.cart.vo.SkuInfoVo;
import cn.edkuir.cart.vo.UserInfoTo;
import cn.edkuir.common.utils.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "mall:cart:";


    @Override
    public void addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> operations = getCartOps();

        String res = (String) operations.get(skuId.toString());
        if(!StringUtils.isEmpty(res)) {
            //购物车已经有了, 增加数量
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount() + num);
            operations.put(skuId.toString(), JSON.toJSONString(item));
            return;
        }

        CartItem cartItem = new CartItem();

        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            //1.远程查询当前要添加的商品的信息
            R r = productFeignService.info(skuId);
            SkuInfoVo data = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });

            cartItem.setImage(data.getSkuDefaultImg());
            cartItem.setTitle(data.getSkuTitle());
            cartItem.setCount(num);
            cartItem.setSkuId(skuId);
            cartItem.setPrice(data.getPrice());
            cartItem.setCheck(true);
        }, executor);

        CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
            //2.查询sku的组合信息(销售属性)
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(skuSaleAttrValues);
        }, executor);

        //3.保存到redis
        CompletableFuture.allOf(getSkuAttrTask, getSkuInfoTask).get();
        String s = JSON.toJSONString(cartItem);
        operations.put(skuId.toString(), s);
    }


    //根据skuId查出单个购物项数据
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        return JSON.parseObject((String) operations.get(skuId.toString()), CartItem.class);
    }


    //获取整个购物车
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        List<CartItem> tempCartItems = getTempCartItems(CART_PREFIX + userInfoTo.getUserKey());
        if(userInfoTo.getUserId() == null) {
            //没登录
            cartVo.setItems(tempCartItems);
            return cartVo;
        }

        //判断临时购物车的数据有没有合并
        if(tempCartItems != null) {
            //临时购物车还有数据
            for (CartItem tempCartItem : tempCartItems) {
                addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
            }
            //清空购物车
            clearCart(CART_PREFIX + userInfoTo.getUserKey());
        }

        //获取登录后的购物车数据(包含合并过来的临时购物车数据)
        List<CartItem> allItems = getTempCartItems(CART_PREFIX + userInfoTo.getUserId());
        cartVo.setItems(allItems);
        return cartVo;
    }


    //清空购物车
    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }


    //勾选购物项
    @Override
    public void check(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        operations.put(skuId.toString(), JSON.toJSONString(cartItem));
    }


    //改变商品数量
    @Override
    public void count(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        operations.put(skuId.toString(), JSON.toJSONString(cartItem));
    }


    //删除购物项
    @Override
    public void delete(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        operations.delete(skuId.toString());
    }


    //获取当前登录用户购物车选中的所有商品
    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null) {
            //没有登录
            return null;
        }
        List<CartItem> cartItems = getTempCartItems(CART_PREFIX + userInfoTo.getUserId());
        if(cartItems == null) {
            return null;
        }
        return cartItems.stream().filter(CartItem::getCheck).map(item -> {
                    //更新为最新价格
                    item.setPrice(productFeignService.getPrice(item.getSkuId()));
                    return item;
                }).collect(Collectors.toList());
    }



    // ========================= private =============================
    /**
     * 获取我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1. 判断用户是否登录
        String cartKey = "";
        if(userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        //2. 获取当前用户的购物车
        return stringRedisTemplate.boundHashOps(cartKey);
    }


    //获取购物车里面的所有购物项
    private List<CartItem> getTempCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(!CollectionUtils.isEmpty(values)) {
            return values.stream()
                    .map((obj) -> JSON.parseObject((String) obj, CartItem.class))
                    .collect(Collectors.toList());
        }
        return null;
    }

}
